<template>
    <div id="mapol">
    </div>
</template>
<script>
// import esb from '@/plugins/esb'
import 'ol/ol.css'
import ol from 'ol'
import Map from 'ol/Map'
import View from 'ol/View'
import { getWidth,getCenter} from 'ol/extent'
import TileLayer from 'ol/layer/Tile'
import { defaults as defaultControls } from 'ol/control'
import WMTS from 'ol/source/WMTS'
import XYZ from 'ol/source/XYZ'
import OSM from 'ol/source/OSM'
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import Projection from 'ol/proj/Projection'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import { LineString, Polygon } from 'ol/geom';
import { getLength } from 'ol/sphere';
import Overlay from 'ol/Overlay';

import Feature from 'ol/Feature'
// import Point from 'ol/geom/Point'
import { Draw,  Modify, Snap } from 'ol/interaction'
import { Style, Circle, Stroke, Fill } from 'ol/style'
import WKT from 'ol/format/WKT'
import GeoJSON from 'ol/format/GeoJSON'
// import { GEOJSON_BL } from '@/const/data/beilin.js'
import GEOJSON_BL from '../../../public/mapBorder/chinaSJ.json'

    export default {
      name: 'mapol',
      data() {
        return {
            userName: "admin",
            draw: null,
            map: null,
            vectorLayer: null,
            GGLWLayer: null,
            GGLayer: null,
            type: 'Point',
            lineLength: 0,
            // 地图初始化 方法：
        }
      },
      mounted(){
        this.init();
        this.addGeoJSON()
      },
      methods: {
        // 地图初始化 方法：
            init () { // 初始化地图
                // 矢量图层
                const projection = new Projection({
                    code: 'EPSG:4326',
                    extent: [-180, -90, 180, 90],
                    metersPerUnit: 2 * Math.PI * 6378137 / 360
                })
            /*   const projectionExtent = projection.getExtent()
                const size = getWidth(projectionExtent) / 256
            
                const resolutions = new Array(18)
                const matrixIds = new Array(18)
                for (let z = 0; z < 18; ++z) {
                    resolutions[z] = size / Math.pow(2, z + 1)
                    matrixIds[z] = z + 1
                }
                // 省级节点提供的瓦片总共14级，从7到20
                const resolutions2 = new Array(20)
                const matrixIds2 = new Array(20)
                for (let z = 0; z < 20; ++z) {
                    resolutions2[z] = size / Math.pow(2, z)
                    matrixIds2[z] = z
                }
                const orgin = [-180, 90]
                */
            
                this.vectorLayer = new VectorLayer({
                    source: new VectorSource(),
                    style: new Style({
                        stroke: new Stroke({
                            width: 2,
                            color: [242, 114, 60, 1],
                            lineDash: [1, 2, 3, 4, 5, 6]
                        }),
                        fill: new Fill({
                            color: [242, 114, 60, 0.2]
                        }),
                        image: new Circle({
                            // 点的颜色
                            fill: new Fill({
                                COLOR: '#f60404',
                                color: [246, 4, 4, 1]
                            }),
                            stroke: new Stroke({
                                color: [242, 114, 60, 1]
                            }),
                            // 圆形半径
                            radius: 5
                        })
                    })
                })
                this.GGLWLayer = new TileLayer({
                    source:new XYZ({
                        url:"http://t4.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
                    }),
                    visible: false
                });
                this.GGLayer = new TileLayer({
                    source:new XYZ({
                        //url:"http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
                        url:"http://t{0-7}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=7315f5ec96fcf2cfce1ff52b4de5d5df"
                    }),
                    visible: true
                });
                this.TDTLayer = new TileLayer({
                    source:new XYZ({
                        url:"http://t4.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
                    }),
                });
                this.zjLayer = new TileLayer({
                    source:new XYZ({
                        url:"http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d"
                    }),
                    visible: false
                });
                this.map = new Map({
                    layers: [
                        this.TDTLayer,
                        this.GGLayer,
                        //   this.GGLWLayer,
                        this.vectorLayer,
                        // this.zjLayer
                    ],
                    target: 'mapol',
                    // controls: defaultControls({
                    //     zoom: false,
                    //     rotate: false,
                    //     attribution: false,
                    //     attributionOptions:{
                    //         collapsible: false
                    //     }
                    // }),
                    view: new View({
                        center: [106.814931000, 34.945231000, 16000],
                        projection: projection,
                        minZoom: 4,
                        maxZoom: 21,
                        // extent : maxExtent, //限定到地图视图拖动范围
                        zoom: 5 // 地图初始化的缩放级别
                    })
                })

               
            },
            // 添加GeoJOSN
            addGeoJSON () {
                this.clearGeoJSON()
                let source = new VectorSource({
                    // 准备好的GeoJSON
                    features: new GeoJSON().readFeatures(GEOJSON_BL)
                })
                // debugger
                this.geoLayer = new VectorLayer({
                    source: source,
                    // 设置样式，边框和填充
                    style: new Style({
                        stroke: new Stroke({
                            color: 'green',
                            width: 3
                        }),
                        fill: new Fill({
                            color: 'rgba(255, 255, 0, 0.1)'
                        })
                    })
                })
                // 添加GeoJSON到map上
                this.map.addLayer(this.geoLayer)
                // 地图视图缩小一点
                const view = this.map.getView()
                view.setZoom(4)
            },
            // 清除GeoJSON
            clearGeoJSON () {
                if (this.geoLayer) {
                    this.map.removeLayer(this.geoLayer)
                    this.geoLayer = null
                }
                // 清除之后将地图中心还原
                const view = this.map.getView()
                view.setCenter([106.814931000, 34.945231000, 16000])
                view.setZoom(12)
            },
            // 切换地图
            changeMap (type) {
                if (type === 'GGLayer') {
                    this.GGLayer.setVisible(true)
                    this.GGLWLayer.setVisible(false)
                    // this.zjLayer.setVisible(false)
                } else if (type === 'GGLWLayer') {
                    this.GGLayer.setVisible(false)
                    this.GGLWLayer.setVisible(true)
                }
            },
            // 绘制点
            point () {
                const m = this
                m.isShow = false
                m.type = 'Point'
                m.drawMap(m.type)
            },
            // 绘制多边形-面
            polygon () {
                const m = this
                m.isShow = false
                m.type = 'Polygon'
                this.drawMap(m.type)
            },
            // 绘制矩形
            square () {
                const m = this
                m.isShow = false
                let type = 'Circle'
                document.oncontextmenu = function () {
                    return false
                }
                this.map.removeInteraction(this.draw)
                this.vectorLayer.getSource().clear()
                this.draw = new Draw({
                    source: this.vectorLayer.getSource(),
                    type: type,
                    stopClick: true, // 绘制时禁用点击事件
                    style: this.getDrawingStyle(),
                    geometryFunction: (coordinates, geometry) => this.rectangleGeometryFunction(coordinates, geometry)
                })
                this.draw.on('drawend', e => {
                    this.feature = e.feature
                    var a = new WKT()
                    this.wkt = a.writeGeometry(this.feature.getGeometry())
                    this.map.removeInteraction(this.draw)
                })
                this.map.addInteraction(this.draw)
                // this.drawMap(m.type)
            },
            // 绘制圆形
            circular(){
                console.log('绘制圆形', this.map.getLayers().item(1).getSource());
                
                const vectorSource = this.map.getLayers().item(1).getSource();
                // document.oncontextmenu = function () {
                //     return false
                // }
                // const m = this
                // this.map.removeInteraction(this.draw)
                console.log('this.feature', vectorSource.getGeometry().getType());

                // this.vectorLayer.getSource().clear()
                this.draw = new Draw({
                    source: vectorSource,
                    type: 'Circle',
                    geometryFunction: (coordinates, geometry) => {}
                });
              
                this.map.addInteraction(this.draw);
                // 编辑功能
                const modify = new Modify({ source: vectorSource });
                this.map.addInteraction(modify);
                // 吸附功能
                const snap = new Snap({ source: vectorSource });
                this.map.addInteraction(snap); 
                this.draw.on('drawend', e => {
                    this.feature = e.feature
                    var a = new WKT()
                    this.wkt = a.writeGeometry(this.feature.getGeometry())
                    this.map.removeInteraction(this.draw)
                })
                this.map.addInteraction(this.draw);

            },
            // 绘制线
            line () {
                const m = this
                m.isShow = false
                m.type = 'LineString'
                this.drawMap(m.type)
                 // 创建用于显示长度的 overlay
                const lengthElement = document.createElement('div');
                lengthElement.className = 'length-overlay';
                this.lengthOverlay = new Overlay({
                    element: lengthElement,
                    positioning: 'bottom-center',
                    stopEvent: false
                });
                this.map.addOverlay(this.lengthOverlay);
            },
            drawMap (type) {
                document.oncontextmenu = function () {
                    return false
                }
                // const m = this
                this.map.removeInteraction(this.draw)
                this.vectorLayer.getSource().clear()
                this.draw = new Draw({
                    source: this.vectorLayer.getSource(),
                    type: type,
                    stopClick: true, // 绘制时禁用点击事件
                    style: this.getDrawingStyle(),
                })
                
                this.draw.on('drawend', e => {
                    // let coordinates = e.feature.getGeometry().getCoordinates();
                    // 绘制线时计算长度
                    if (type === 'LineString') {
                        const line = e.feature.getGeometry();
                            if (line instanceof LineString) {
                            // this.lineLength = getLength(line);
                            const length = getLength(line) * 100;
                            const lengthElement = this.lengthOverlay.getElement();
                            lengthElement.innerHTML = `长度: ${length.toFixed(2)}千米`;

                            // 计算线的中心点作为 overlay 的位置
                            const coordinates = line.getCoordinates();
                            const centerIndex = Math.floor(coordinates.length / 2);
                            const center = coordinates[centerIndex];
                            this.lengthOverlay.setPosition(center);
                        }
                    }
                    this.feature = e.feature
                    var a = new WKT()
                    this.wkt = a.writeGeometry(this.feature.getGeometry())
                    this.map.removeInteraction(this.draw)
                   
                    
                 
                })
                this.map.addInteraction(this.draw)
            },
            // 绘制 点、面 样式
            getDrawingStyle () {
                return new Style({
                    stroke: new Stroke({
                        width: 2,
                        color: [239, 176, 19, 1],
                        lineDash: [1, 2, 3, 4, 5, 6]
                    }),
                    fill: new Fill({
                        color: [239, 176, 19, 0.2]
                    }),
                    image: new Circle({
                    // 点的颜色
                    fill: new Fill({
                        color: [246, 4, 4, 1]
                    }),
                    stroke: new Stroke({
                        color: [239, 176, 19, 1]
                    }),
                        // 圆形半径
                        radius: 5
                    })
                })
            },
            // 绘制矩形样式
            rectangleGeometryFunction(coordinates, geometry){
                if (!geometry) {
                    geometry = new Polygon([]);
                }
                const start = coordinates[0];
                const end = coordinates[1];
                geometry.setCoordinates([
                    [
                        [start[0], start[1]],
                        [start[0], end[1]],
                        [end[0], end[1]],
                        [end[0], start[1]],
                        [start[0], start[1]]
                    ]
                ]);
                return geometry;
            }
        }
    }
</script>
<style lang="scss" scoped>
#mapol{
    width: 100%;
    height: 100%;
}
</style>